//
//  WSIssuedViewController.m
//  WisdomStar
//
//  Created by 谭飞 on 2018/10/24.
//  Copyright © 2018年 zhangliwen. All rights reserved.
//

#import "WSIssuedViewController.h"
#import "TZImagePickerController.h"
#import "SHPickerView.h"
#import "AddImageCell.h"

#import "SHUploadFileManager.h"
#import "ACMediaManager.h"
#import "JDTimeFormatTool.h"
#import "CourseService.h"
#import "UploadService.h"
#import "WSUserInfo.h"
#import "WSTeacherInfo.h"

/// 授课模式
typedef NS_ENUM(NSUInteger, TeachingPattern) {
    OneToOne = 1, // 一对一
    Group = 2 // 团课
};

@interface WSIssuedViewController ()<TZImagePickerControllerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate,
UICollectionViewDataSource, UICollectionViewDelegate>

// subviews
@property (nonatomic, strong) UIButton *rightNavButton;
@property (weak, nonatomic) IBOutlet UITableViewCell *cell;
@property (weak, nonatomic) IBOutlet UIStackView *stackView;
@property (weak, nonatomic) IBOutlet UIView *stackContentView;
@property (weak, nonatomic) IBOutlet UIView *detailStackSubView;
@property (weak, nonatomic) IBOutlet UIView *videoContentView;
@property (weak, nonatomic) IBOutlet UIView *coverContentView;
@property (weak, nonatomic) IBOutlet UIView *detailContentView;
@property (weak, nonatomic) IBOutlet UIImageView *addIconView;
@property (weak, nonatomic) IBOutlet UIImageView *videoIconView;
@property (weak, nonatomic) IBOutlet UIView *addImageContentView;
@property (weak, nonatomic) IBOutlet UIImageView *coverImage;
@property (weak, nonatomic) IBOutlet UIImageView *mediaPreview;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *detailContentHeight;

// inputText
@property (weak, nonatomic) IBOutlet UITextView *detalTextView;
@property (weak, nonatomic) IBOutlet UITextField *wayText;
@property (weak, nonatomic) IBOutlet UITextField *cateText;
@property (weak, nonatomic) IBOutlet UITextField *durationText;
@property (weak, nonatomic) IBOutlet UITextField *gradeText;
@property (weak, nonatomic) IBOutlet UITextField *teacherText;
@property (weak, nonatomic) IBOutlet UITextField *courseNameText;
@property (weak, nonatomic) IBOutlet UITextField *timeText;
@property (weak, nonatomic) IBOutlet UITextField *patternText;
@property (weak, nonatomic) IBOutlet UITextField *totalText;
@property (weak, nonatomic) IBOutlet UITextField *priceText;

// data source
@property (nonatomic, strong) NSArray *cateList;     // 课程类别
@property (nonatomic, strong) NSArray *gradeList;    // 年级列表
@property (nonatomic, strong) NSArray *wayList;      // 授课方式
@property (nonatomic, strong) NSArray <WSTeacherInfo *> *teacher_list; // 教师信息列表
@property (nonatomic, strong) NSMutableArray *detailImages; // 详情图片
@property (nonatomic, strong) NSMutableArray *uploadImages; // 要上传的图片

@property (nonatomic, assign) TeachingPattern pattern; // 授课模式
@property (nonatomic, copy) NSString *wayId; // 授课id
@property (nonatomic, copy) NSString *cateId; // 分类id
@property (nonatomic, copy) NSString *gradeId; // 年级id
@property (nonatomic, strong) NSData *videoData; // 要上传的视频数据
@property (nonatomic, strong) NSDictionary *qnUploadInfo;
@property (nonatomic, assign) BOOL addCover; // 是否是添加封面
@property (nonatomic, assign) NSInteger selectIndex;

@end

@implementation WSIssuedViewController

#pragma mark - Life cycle
- (void)dealloc {
    NSLog(@"======%s",__FUNCTION__);
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setup];
    [self loadData];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.tableView.contentSize = CGSizeMake(0, self.cell.xmg_bottom);
}

- (void)setup {
    // navbar
    self.navigationItem.title = @"发布课程";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightNavButton];
    self.tableView.tableFooterView = [UIView new];
    self.detalTextView.placeHolderText = @"请输入...";
    
    [self.collectionView registerNib:[UINib nibWithNibName:[AddImageCell className] bundle:nil] forCellWithReuseIdentifier:[AddImageCell className]];
    
    // add border
    [self.videoContentView setBorder:kSeparatorColor borderWidth:0.5f borderType:UIBorderSideTypeAll];
    [self.addImageContentView setBorder:kSeparatorColor borderWidth:0.5f borderType:UIBorderSideTypeAll];
    [self.detailContentView setBorder:kSeparatorColor borderWidth:0.5f borderType:UIBorderSideTypeAll];
    
    // tap gestures
    WEAKSELF
    [self.videoContentView addGestureWithGestureType:WJ_TapGesture completeHandler:^{
        [weakSelf openVideo];
    }];
    
    [self.coverContentView addGestureWithGestureType:WJ_TapGesture completeHandler:^{
        weakSelf.addCover = YES;
        [weakSelf openAlbum];
    }];
    
    if (self.isTeacher) {
        WSUserInfo *user = [WSUserInfo yy_modelWithJSON:[TFUserDefault valueForKey:@"userInfo"]];
        self.teacherText.text = user.nickname;
    }
}

- (void)loadData {
    dispatch_group_t group = dispatch_group_create();
    
    // 获取课程类别
    dispatch_group_enter(group);
    [CourseService fetchCourseCateWithResult:^(id  _Nonnull responseObj) {
        ResponseModel *response = [ResponseModel yy_modelWithJSON:responseObj];
        if (!response.data) {
            dispatch_group_leave(group);
            return;
        }
        NSMutableArray *cateArr = [NSMutableArray array];
        [response.data enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [cateArr addObject:obj];
        }];
        self.cateList = [cateArr copy];
        
        dispatch_group_leave(group);
    }];
    
    // 获取发布课程信息
    dispatch_group_enter(group);
    [CourseService fetchAddCourseInfoWithResult:^(id  _Nonnull resonseObj) {
        ResponseModel *response = [ResponseModel yy_modelWithJSON:resonseObj];
        if (!response.data) {
            dispatch_group_leave(group);
            return;
        }
        // 年级列表
        NSMutableArray *gradeArr = [NSMutableArray array];
        [response.data[@"grade_list"] enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [gradeArr addObject:obj];
        }];
        self.gradeList = [gradeArr copy];
        
        // 授课方式
        NSMutableArray *ways = [NSMutableArray array];
        [response.data[@"way_list"] enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [ways addObject:obj];
        }];
        self.wayList = [ways copy];
        
        // 教师列表
        self.teacher_list = [NSArray yy_modelArrayWithClass:[WSTeacherInfo class] json:response.data];
        
        dispatch_group_leave(group);
    }];
    
    // 请求完成
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        self.pattern = OneToOne; // 默认：一对一授课
    });
}


/**
 获取视频上传token

 @param size 视频文件大小
 */
- (void)getVideoToken:(int)size {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"token"] = User_Token;
    param[@"size"] = @(size);
    param[@"ext"] = @"mp4";
    [UploadService getQnUploadInfoWithType:UploadTypeVideo params:param completion:^(id  _Nonnull result) {
        ResponseModel *response = [ResponseModel yy_modelWithJSON:result];
        if (!response.data) {
            return ;
        }
        self.qnUploadInfo = response.data;
    }];
}

#pragma mark - Actions

/**
 发布课程
 */
- (void)rightNavButtonClick {
    __block NSString *imageUrlStr, *videoUrlStr,*imageListStr;
    
    [SVProgressHUD showLoading:@"请稍后..."];
    dispatch_group_t group = dispatch_group_create();
    // 上传视频
    if (self.videoData) {
        dispatch_group_enter(group);
        QNUploadManager *qnManager = [[QNUploadManager alloc] init];
        [qnManager putData:self.videoData key:[SHUploadFileManager qnVideoFilePatName] token:self.qnUploadInfo[@"token"] complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
            videoUrlStr = [NSString stringWithFormat:@"%@/%@",self.qnUploadInfo[@"url"], key];
            dispatch_group_leave(group);
        } option:nil];
    }
    
    // 上传图片
    if (self.coverImage.image) {
        UIImage *image = self.coverImage.image;
        dispatch_group_enter(group);
        [SHUploadFileManager uploadWithImage:image token:QNToken completion:^(NSString *result) {
            imageUrlStr = [NSString stringWithFormat:@"%@/%@",[TFUserDefault valueForKey:@"imageUrl"], result];
            dispatch_group_leave(group);
        }];
    }
    
    // 上传课程简介图片
    if (self.detailImages.count>1) {
        dispatch_group_enter(group);
        [self.detailImages removeLastObject];
        [SHUploadFileManager uploadWithImages:self.detailImages token:QNToken complete:^(NSArray *imageKeys) {
            imageListStr = [imageKeys componentsJoinedByString:@","];
            dispatch_group_leave(group);
        }];
    }
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        params[@"token"] = User_Token;
        params[@"cate_id"] = self->_cateId;
        params[@"way"] = self->_wayId;
        params[@"grade_id"] = self->_gradeId;
        params[@"name"] = self.teacherText.text;
        params[@"teach_type"] = @(self->_pattern);
        params[@"price"] = self.priceText.text;
        params[@"start_time"] = self.timeText.text;
        params[@"image"] = imageUrlStr;
        params[@"introduction"] = self.detalTextView.text;
        params[@"image_list"] = imageListStr;
        if (self.videoData) {
            params[@"video"] = videoUrlStr;
        }
        if (self.pattern == Group) {
            params[@"total"] = self.totalText.text;
        }
        [CourseService addCourseWithParams:params completion:^(BOOL success, id  _Nonnull responseObj) {
            if (success) {
                [SVProgressHUD showSuccess:@"发布成功"];
                KDISPATCH_DELAY(2.f, ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
            } else {
                
            }
        }];
    });
}


#pragma mark - Utils

/** 相册 */
- (void)openAlbum {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    ///是否 在相册中显示拍照按钮
    imagePickerVc.allowTakePicture = YES;
    ///是否可以选择显示原图
    imagePickerVc.allowPickingOriginalPhoto = NO;
    ///是否 在相册中可以选择视频
    imagePickerVc.allowPickingVideo = NO;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

/** 视频 */
- (void)openVideo {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:picker.sourceType];
    picker.allowsEditing = YES;
    [self presentViewController:picker animated:YES completion:nil];
}

- (void)showPickerWithTitle:(NSString *)title items:(NSArray *)items atIndex:(NSInteger)index {
    SHPickerView *picker = [[SHPickerView alloc] initWithTitle:title items:items block:^(SHPickerView *pickerView, NSInteger selectRow) {
        if (index == 0) {
            self.wayText.text = items[selectRow];
            if ([self.wayText.text isEqualToString:@"点播"]) {
                [self.stackView insertArrangedSubview:self.stackContentView atIndex:0];
                self.stackContentView.hidden = NO;
                self.cell.xmg_height = 580.f;
            } else {
                [self.stackView removeArrangedSubview:self.stackContentView];
                self.stackContentView.hidden = YES;
                self.cell.xmg_height = 395.f;
            }
        } else if (index == 1) { // 授课方式
            self.cateText.text = items[selectRow];
            self.cateId = self.cateList[selectRow][@"id"];
        } else if (index == 2) { // 选择年级
            self.gradeText.text = items[selectRow];
            self.gradeId = self.gradeList[selectRow][@"grade_id"];
        } else if (index == 3) { // 授课老师
            self.teacherText.text = items[selectRow];
        } else if (index == 7) { // 授课模式
            self.patternText.text = items[selectRow];
            self.pattern = selectRow == 0 ? Group : OneToOne;
            if (self.pattern == OneToOne) {
                self.totalText.text = @"1";
                self.totalText.enabled = NO;
            } else {
                self.totalText.enabled = YES;
            }
        }
    }];
    [picker show];
}

- (void)handleWithIndex:(NSInteger)index {
    if (index == 0) { // 选择授课方式
        NSMutableArray *items = [NSMutableArray arrayWithCapacity:self.wayList.count];
        [self.wayList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [items addObject:obj[@"way_name"]];
        }];
        [self showPickerWithTitle:@"授课方式" items:items atIndex:index];
    }
    if (index == 1) { // 选择课程类别
        NSMutableArray *items = [NSMutableArray arrayWithCapacity:self.cateList.count];
        [self.cateList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [items addObject:obj[@"name"]];
        }];
        [self showPickerWithTitle:@"课程类别" items:items atIndex:index];
    }
    if (index == 2) { // 选择年级
        NSMutableArray *items = [NSMutableArray arrayWithCapacity:self.gradeList.count];
        [self.gradeList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [items addObject:obj[@"grade"]];
        }];
        [self showPickerWithTitle:@"所属年级" items:items atIndex:index];
    }
    if (index == 3) { // 选择教师
        if (self.isTeacher) {
            return;
        }
        
        NSMutableArray *items = [NSMutableArray arrayWithCapacity:self.teacher_list.count];
        [self.teacher_list enumerateObjectsUsingBlock:^(WSTeacherInfo * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [items addObject:obj.true_name];
        }];
        if (items.count) {
            [self showPickerWithTitle:@"授课老师" items:items atIndex:index];
        }
    }
    if (index == 5) { // 选择授课时间
        SHPickerView *datePicker = [[SHPickerView alloc] initDatePickerWithTitle:@"授课时间" block:^(NSDate *selectDate) {
            self.timeText.text = [JDTimeFormatTool coverToDateWithDate:selectDate format:@"MM-dd HH:mm"];
        }];
        [datePicker show];
    }
    if (index == 7) { // 选择授课模式
        [self showPickerWithTitle:@"授课模式" items:@[@"团课", @"一对一"] atIndex:index];
    }
}

#pragma mark - Table view Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self handleWithIndex:indexPath.row];
}

#pragma mark - UICollectionViewDataSource, UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.detailImages.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    AddImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:[AddImageCell className] forIndexPath:indexPath];
    cell.imgView.image = self.detailImages[indexPath.row];
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    self.addCover = NO;
    self.selectIndex = indexPath.row;
    [self openAlbum];
}

#pragma mark - TZImagePickerController Delegate
//处理从相册单选或多选的照片
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    for (NSInteger index = 0; index < assets.count; index++) {
        PHAsset *asset = assets[index];
        [ACMediaManager getMediaInfoFromAsset:asset completion:^(NSString *name, id pathData) {
            if (index == assets.count - 1) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (self.addCover) {
                        self.coverImage.image = photos[index];
                        self.addIconView.hidden = YES;
                    } else {
                        UIImage *selectImage = photos[index];
                        if (![self.detailImages containsObject:selectImage]) {
                            [self.detailImages replaceObjectAtIndex:self.selectIndex withObject:selectImage];
                        }
                        if (self.selectIndex == self.detailImages.count-1 && self.detailImages.count) {
                            [self.detailImages addObject:kPlaceHolderImage];
                            if (self.detailImages.count%3==1) {
                                self.cell.xmg_height += 82.f;
                            }
                        }
                        [self.collectionView reloadData];
                    }
                });
            }
        }];
    }
}

#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:NULL];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    //媒体类型
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    //原图URL
    NSURL *imageAssetURL = [info objectForKey:UIImagePickerControllerReferenceURL];
    
    ///视频 和 录像
    if ([mediaType isEqualToString:@"public.movie"]) {
        NSURL *videoAssetURL = [info objectForKey:UIImagePickerControllerMediaURL];
        PHAsset *asset;
        //录像没有原图 所以 imageAssetURL 为nil
        if (imageAssetURL) {
            PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:@[imageAssetURL] options:nil];
            asset = [result firstObject];
        }
        [ACMediaManager getVideoPathFromURL:videoAssetURL PHAsset:asset enableSave:NO completion:^(NSString *name, UIImage *screenshot, id pathData) {
            int size = (int)([pathData length]/(pow(1024, 2)));
            NSLog(@"压缩后的文件大小: %dMB",size);
            self.videoData = pathData;
            [self getVideoToken:size];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.mediaPreview.image = screenshot;
                self.videoIconView.hidden = YES;
            });
        }];
    }
}


#pragma mark - Getter
- (UIButton *)rightNavButton {
    if (_rightNavButton == nil) {
        _rightNavButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [_rightNavButton setTitle:@"发布" forState:UIControlStateNormal];
        [_rightNavButton setTitleColor:COLOR_HEX(0xE5FFFB) forState:UIControlStateNormal];
        [_rightNavButton.titleLabel setFont:WSFontMake(15)];
        _rightNavButton.xmg_height = kNavBarHeight;
        [_rightNavButton addTarget:self action:@selector(rightNavButtonClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightNavButton;
}

- (NSMutableArray *)detailImages {
    if (_detailImages == nil) {
        _detailImages = [NSMutableArray arrayWithObject:kPlaceHolderImage];
    }
    return _detailImages;
}


@end
